library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;
--use ieee.numeric_std.all;
--use ieee.numeric_bit.all;
entity key_control is
port(clk,start :in std_logic;
	KBCol :in std_logic_vector(0 to 3);
	song:out std_logic;
	play:out std_logic;--1music_play; 0:Elc_keyboard;
	sel:out std_logic;--1:music_play; 0:Elc_keyboard;
	Key_Note:buffer integer range 0 to 16;
	KBRow:buffer std_logic_vector(0 to 3):="0111"	
);
end entity;

architecture control of key_control is

signal clk_kb :std_logic:='0';
signal key:integer range 0 to 16:=0;
signal state:std_logic_vector(0 to 1):="00";
signal song_chg :std_logic:='0';
begin
process(clk) --
variable cnt :integer range 0 to 1000:=0;
begin 
if start='1' then
	if rising_edge(clk)then
		if cnt=50 then
			clk_kb<=not clk_kb;
			cnt:=0;
		else
			cnt:=cnt+1;
		end if;
	end if;
else
	clk_kb<='0';
end if;
end process;


process(clk_kb)
begin
	if rising_edge(clk_kb) then
		if state="11" then
			state<="00";
		else
			state<=state+1;
		end if;
	end if;
end process;

process(clk_kb)
begin
if rising_edge(clk_kb)then
case state is 
	when "00"=>KBRow<="0111";
	when "01"=>KBRow<="1011";
	when "10"=>KBRow<="1101";
	when "11"=>KBRow<="1110";
	when others=>KBRow<=null;
end case;
end if;
end process;

process(clk_kb)
begin
if rising_edge(clk_kb)then
	case KBRow is
		when "0111"=>
		case KBCol is
			when "0111"=>key<=1;
			when "1011"=>key<=2;
			when "1101"=>key<=3;
			when "1110"=>key<=4;
			when others=>key<=0;
		end case;
		when "1011"=>
		case KBCol is
			when "0111"=>key<=5;
			when "1011"=>key<=6;
			when "1101"=>key<=7;
			when "1110"=>key<=8;
			when others=>key<=0;
		end case;
		when "1101"=>
		case KBCol is
			when "0111"=>key<=9;
			when "1011"=>key<=10;
			when "1101"=>key<=11;
			when "1110"=>key<=12;
			when others=>key<=0;
		end case;
		when "1110"=>
		case KBCol is
			when "0111"=>key<=13;
			when "1011"=>key<=14;
			when "1101"=>key<=15;
			when "1110"=>key<=16;
			when others=>key<=0;
		end case;
		when others=>key<=0;
	end case;
end if;
end process;

process(key)

begin
if start='1'then
	if( key>0 and key<8 )then
		Key_Note<=key;
	elsif(key=9)then
		play<='1';
		sel<='1';
	elsif(key=10)then
		play<='0';
		sel<='0';
	elsif(key=11)then
		song_chg<='1';
		song_chg<='1';
		song_chg<='1';
		song_chg<='0';
	end if;
else
	play<='1';
	sel<='0';
	Key_Note<=0;
	song_chg<='0';
end if;
end process;

--process(clk_kb)
--variable cnt :integer range 0 to 10;
--begin
--if(clk_kb)then
	


--end if;

--end process;

end architecture;



